<!-- 藏品初编基本信息组件 -->
<script lang="ts" setup>
import { ref, reactive, onMounted, shallowRef, toRaw, watch } from 'vue'
import { type FormInst, NFormItem, NInput, NSelect, NSpin, type SelectOption } from 'naive-ui'
import { sendRequest } from '@/utils/api'
import { keysOf } from '@/utils/object'
import { mergeWith, isArray } from 'lodash-es'
import DynamicPageForm from '@/components/DynamicPageForm/DynamicPageForm.vue'
import type { ModelJson } from '@/components/DynamicPageForm/DynamicFormTypes'
const props = defineProps({
  id: { type: String, default: () => null },
  typeShow: { type: Number, default: () => 0 },
  code: { type: String, default: () => null }
})
const isUpdate = false
const isDetail = true
const array = props?.id?.split(',') || []
const emit = defineEmits<{
  (event: 'close'): void
  (event: 'update'): void
}>()
const form: any = reactive({
  id: array?.[0],
  password: array?.[0] ? null : 'Aa123456!',
  userStatus: 1,
  typeTree: null,
  typeTreeS: null,
  typeTreeT: null,
  time: null,
  receiveTime: null,
  itemName: null,
  receiveUser: null,
  collectTypeName: null,
  phone: null,
  person: null,
  dujiaoName: null,
  Uptime: null,
  price: null,
  author: null,
  number1: null,
  yesNO: null,
  yinciTime: null,
  remack: null,
  ziicaCode: null,
  water: null,
  position: null
})
const oneSelectValue = ref<string | null>(null)
const oneSelectOptions = shallowRef<[]>([])
const oneSelectLoading = ref(false)

const twoSelectValue = ref<string | null>(null)
const twoSelectOptions = shallowRef<[]>([])
const twoSelectLoading = ref(false)

const threeSelectValue = ref<string | null>(null)
const threeSelectOptions = shallowRef<[]>([])
const threeSelectLoading = ref(false)

const isUseLastSelect = ref(true)

const clueMethodOptions: any = reactive([])

const formInst = ref<FormInst | null>(null)
const formData = ref({} as any)
const handleUpdateFormData = (key: string, value: unknown) => {
  formData.value[key] = value
}
const validatorTypeFormItem = () => {
  if (isUseLastSelect.value) return threeSelectValue.value !== null
  return twoSelectValue.value !== null
}
const modelJson = ref({} as ModelJson)
const queryJson = async (code: string) => {
  try {
    const [error, res]: any = await sendRequest({
      module: 'collection',
      api: 'jsonContent',
      override: {
        params: {
          name: `${code}.json`
        }
      }
    })
    if (error) throw error
    if (res.code !== 200) throw new Error(res.message)
    
    modelJson.value = res.data
    return res.data
  } catch (error) {
    console.error(error)
    return toRaw(baseModel)
  }
}
const baseModel: ModelJson = {
  elements: [
    {
      type: 'NInput',
      key: 'itemName',
      label: '名称：',
      rule: {
        required: true,
        message: '名称必填'
      }
    },
    {
      type: 'NDatePicker',
      key: 'receiveTime',
      label: '接收时间：',
      props: { type: 'datetime', format: 'yyyy-MM-dd HH:mm:ss' },
      style: { flex: 1 },
      rule: {
        required: true,
        message: '接收时间必填'
      }
    },
    {
      type: 'NSelect',
      key: 'collectTypeName',
      label: '征集方式：',
      props: {
        options: clueMethodOptions,
        valueField: 'code',
        labelField: 'name'
      },
      rule: {
        required: true,
        message: '征集方式必填'
      }
    },
    {
      type: 'NInputNumber',
      key: 'itemNum',
      label: '数量：',
      style: { flex: 1 },
      props: {
        showButton: false,
        min: 0
      },
      rule: {
        type: 'number',
        required: true,
        message: '数量必填'
      }
    },
    {
      type: 'NInput',
      key: 'receiveUser',
      label: '接收人：',
      rule: {
        required: true,
        message: '接收人必填'
      }
    },
    {
      type: 'NInput',
      key: 'notes',
      label: '备注：',
      props: {
        type: 'textarea',
        rows: 1
      },
      rule: {
        required: true,
        message: '备注必填'
      }
    }
  ]
}
const model = shallowRef<any>(baseModel)
const setModelJson = async (code?: string | null) => {
  if (!code) return (model.value = toRaw(baseModel))
  model.value = mergeWith({}, toRaw(baseModel), await queryJson(code), (obj: any, src: any) => {
    if (isArray(obj)) return [...obj, ...src]
  }) as ModelJson
}
const clueInfoLoading = ref(false)
const checkIsDetail = async (code: any) => {
  
  try {
    const [error, res] = await sendRequest({
      module: 'collectProcess',
      api: 'info',
      uri: {
        itemCode: code as string
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    
    await setModelJson(res.data.itemTypeCode)
    const { data } = res
    formData.value = Object.assign(
      {},
      {
        itemName: data.itemName,
        receiveTime: data.receiveTime,
        itemTypeCode: data.itemTypeCode,
        itemTypeName: data.itemTypeName,
        itemNum: data.itemNum,
        collectTypeName:data.collectTypeName,
        receiveUser: data.receiveUser,
        notes: data.notes,
        itemTypeItem:data.itemTypeName,
      },
      JSON.parse(data.jsonStr || '{}')
    )
    // fileList.value = data.fileList?.map((e: any, i: number) => ({
    //   id: i,
    //   name: e.name,
    //   status: 'finished',
    //   url: e.path,
    //   remoteId: e.id
    // }))
  } catch (error) {
    console.error(error)
  } finally {
    setTimeout(() => {
      clueInfoLoading.value = false
    }, 2000)
  }
}
 watch(()=>props.id,()=>{
  sendRequest({
      module: 'collectProcess',
      api: 'collectingItemsInfo',
      uri: {
        id: props.id
      }
    }).then(([err, res]) => {
      if (err) return
      keysOf(res.data).forEach((e) => {
        form[e] = res.data[e] as never
      })
      checkIsDetail(res.data?.itemCode)
      // queryMenuOptions(role.id)
    })
 })
onMounted(async () => {
  // 修改回显
  if (props.id) {
    sendRequest({
      module: 'collectProcess',
      api: 'collectingItemsInfo',
      uri: {
        id: props.id
      }
    }).then(([err, res]) => {
      if (err) return
      keysOf(res.data).forEach((e) => {
        form[e] = res.data[e] as never
      })
      checkIsDetail(res.data?.itemCode)
      // queryMenuOptions(role.id)
    })
  }
})
</script>

<template>
  <div>
    <NSpin :show="false">
      <!-- <div class="topTitle">基本信息</div> -->
      <DynamicPageForm
        ref="formInst"
        :form-model="model"
        :model="formData"
        :form-data="formData"
        :disabled="isDetail && !isUpdate"
        label-placement="left"
        require-mark-placement="left"
        label-width="140rem"
        @update:value="handleUpdateFormData"
        class="ac-card"
      >
        <NFormItem
          label="类型："
          path="type"
          :rule="
            !isDetail && !isUpdate
              ? { required: true, message: '类型必填', validator: () => validatorTypeFormItem() }
              : undefined
          "
        >
          <template v-if="!isDetail && !isUpdate">
            <NSelect
              v-model:value="oneSelectValue"
              :options="(oneSelectOptions as unknown as SelectOption[])"
              :loading="oneSelectLoading"
              :disabled="isDetail || oneSelectLoading"
              style="margin-right: 10rem"
            />
            <NSelect
              v-model:value="twoSelectValue"
              :options="(twoSelectOptions as unknown as SelectOption[])"
              :loading="twoSelectLoading"
              :disabled="isDetail || oneSelectLoading || twoSelectLoading"
              style="margin-right: 10rem"
            />
            <NSelect
              v-model:value="threeSelectValue"
              :options="(threeSelectOptions as unknown as SelectOption[])"
              :disabled="isDetail || oneSelectLoading || twoSelectLoading || threeSelectLoading"
              :loading="threeSelectLoading"
            />
          </template>

          <NInput
            v-else
            disabled
            :value="formData.itemTypeItem"
          />
        </NFormItem>
      </DynamicPageForm>
    </NSpin>
  </div>
</template>
<style scoped lang="scss">
@mixin CommonFont {
  font-size: 18rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: #333333;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .form_content {
    width: 100%;
    height: 100%;
    padding: 20rem 20rem 0;

    .content {
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 100%;
      padding: 18rem 33rem 120rem;
      overflow-y: scroll;
      background-color: #ebeceb;
      @include CommonFont;
    }
  }
}

.inputWH {
  width: 300rem;
}

.topTitle {
  font-size: 22px;
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  color: #5fb17f;
  margin-bottom: 10rem;
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
